package com.itheima.controller;


import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * 用来处理文件的上传和下载
 */
@Slf4j
@RequestMapping("/common")
@RestController
public class CommonController {

    @Value("${uploadPath}")
    private String uploadPath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置否则本次请求完成后临时文件会被删除
        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();

        //获取后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复导致文件被覆盖
        String newName = UUID.randomUUID().toString() + suffix;

        //创建一个目录对象
        File dir=new File("D:/heimadata/img");

    /*    File dir=new File(uploadPath);*/

        //判断当前目录是否存在，不存在就创建
        if (!dir.exists()){

        }


        //将临时文件转存到指定位置
        try {
            file.transferTo(new File(uploadPath+'/'+newName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(newName);
    }


    /**
     * 下载文件
     * @param name
     */
    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            InputStream fileInputStream=new FileInputStream(new File(uploadPath+'/'+name));

            //输出流，通过输出流将文件写回浏览器
            /*ServletOutputStream outputStream=response.getOutputStream();
            response.setContentType("image/jpeg");//输出的文件类别，可省略*/

            //定义一个缓冲区，把输入流不断定义到缓冲区
            byte[] bytes = new byte[8192];
            int len=0;
            while ((len=fileInputStream.read(bytes))!=-1){

                //把缓冲区内容不断写给页面
                response.getOutputStream().write(bytes,0,len);
               /* outputStream.write(bytes,0,len);
                outputStream.flush();*/
            }

            //关闭资源
           /* outputStream.close();*/
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }



    }


}
